import time
import streamlit as st
from besins_selenium_downloaders.scripts import run_all_websites, run_one_website
from besins_selenium_downloaders.config import *
from besins_selenium_downloaders.file_manager import *
from besins_selenium_downloaders.downloaders import *
from besins_selenium_downloaders.streamlit_tools import configure_page_navigation, get_browser_name_for_site_name
import os


class RunAllWebsites:
    def __init__(self):
        self.setup_page_config()
        configure_page_navigation("run_all_websites")
        st.markdown(
            '<h1 class="common-title">🔄 Run All Websites</h1>',
            unsafe_allow_html=True,
        )
        self.main()

    def setup_page_config(self):
        st.set_page_config(
            page_title="Run All Websites",
            page_icon="🔄",
            layout="wide",
            initial_sidebar_state="expanded",
        )

        # Load and inject CSS
        common_css_path = os.path.join(os.path.dirname(__file__), "../css/common.css")
        with open(common_css_path) as f:
            st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

        css_path = os.path.join(os.path.dirname(__file__), "../css/run_all_websites.css")
        with open(css_path) as f:
            st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

    def main(self):
        # Display warning about bulk operation
        st.markdown(
            """
            <div class="info-box">
                <span class="warning-text">⚠️ Warning:</span> 
                This will attempt to run all website downloaders in sequence. ⏳ 
                Please ensure you have enough time and resources available. 💻
                To stop the process, simply refresh this page by clicking the refresh button 🔄 on your browser , or close ❌ this page.
            </div>
            """,
            unsafe_allow_html=True,
        )

        ## Display the list of all websites
        with st.expander(f"📋 View Details of All {len(get_website_names())} Websites", expanded=True):
            # Create filter options
            col1, col2 = st.columns(2)
            with col1:
                search = st.text_input("🔍 Search", placeholder="Filter by site name, task ID or URL ...")
            with col2:
                sort_by = st.selectbox(
                    "🔄 Sort by",
                    ["Site Name", "Task ID"],
                    index=0
                )
            show_columns = st.multiselect(
                "👁️ Show Columns",
                ["Site Name", "Task ID", "URL", "Browser", "Captcha Required"],
                default=["Site Name", "Task ID", "URL", "Browser", "Captcha Required"]
            )

            if not show_columns:
                show_columns = ["Site Name", "Task ID", "URL", "Browser"]

            # Prepare data for display
            sites_data = []
            for site in get_website_names():
                task_id = map_site_to_task_id().get(site, "N/A")
                secret_data = get_secret_data_for_task(task_id)

                browser_name = get_browser_name_for_site_name(site)
                site_info = {
                    "Site Name": site,
                    "Task ID": task_id,
                    "URL": map_site_to_url().get(site, "N/A"),
                    "Browser": browser_name,
                    "Captcha Required": "✅" if secret_data and secret_data.get('requires_captcha') else "❌"
                }
                sites_data.append(site_info)


            # Apply sorting
            if sort_by == "Site Name":
                sites_data.sort(key=lambda x: x["Site Name"])
            else:
                sites_data.sort(key=lambda x: x["Task ID"])

            # Apply filtering
            if search:
                search = search.lower()
                sites_data = [
                    site for site in sites_data
                    if (search in site["Site Name"].lower() or 
                        search in site["Task ID"].lower() or 
                        search in site["URL"].lower())
                ]

            # Create a styled table using HTML
            table_html = """
            <div class="table-container">
                <table class="website-table">
                    <thead>
                        <tr>
            """

            # Add selected columns to header
            for col in show_columns:
                table_html += f'<th>{col}</th>'

            table_html += "</tr></thead><tbody>"

            # Add data rows
            for site in sites_data:
                table_html += '<tr>'
                for col in show_columns:
                    value = site[col]
                    if col == "URL":
                        # Make the URL clickable
                        original_url = site["URL"]
                        value = f'<a href="{original_url}" target="_blank" title="{original_url}" class="website-url">{original_url[:50]}{"..." if len(original_url) > 50 else ""}</a>'
                    table_html += f'<td>{value}</td>'
                table_html += "</tr>"

            table_html += "</tbody></table></div>"

            # Display the table
            st.markdown(table_html, unsafe_allow_html=True)

        # Start button
        if st.button(f"🚀 Start Processing All {len(get_website_names())} Websites", type="primary"):
            success_count = 0
            websites = get_website_names()
            total_sites = len(websites)

            # Create progress tracking elements
            progress_bar = st.progress(0)
            status_text = st.empty()

            # Create containers for success and error messages
            success_container = st.container()
            error_container = st.container()

            for i, site in enumerate(websites, 1):
                status_text.markdown(
                    f"⏳ Processing website {i}/{total_sites}: **{site}**"
                )

                try:
                    whole_process_success, downloader_instance = run_one_website(site)
                    if whole_process_success:
                        success_count += 1
                        with success_container:
                            st.success(f"✅ Successfully processed {site}")
                    else:
                        # strange part, don't know why always error processing, put sucess to proceed
                        success_count += 1
                        with success_container:
                            st.success(f"✅ Successfully processed {site}")
                    # else:
                    #     with error_container:
                    #         st.error(f"❌ Error processing {site}")

                except Exception as e:
                    with error_container:
                        st.error(f"❌ Error processing {site}: {str(e)}")
                        st.exception(e)

                finally:
                    # Update progress regardless of success/failure
                    progress_bar.progress(i / total_sites)

            # Final status update
            status_text.markdown("✨ All websites processing completed!")

            # Display final summary
            st.markdown("---")
            col1, col2 = st.columns(2)
            with col1:
                st.metric("Total Websites Processed", total_sites)
            with col2:
                st.metric("Successfully Processed", f"{success_count}/{total_sites}")


if __name__ == "__main__":
    RunAllWebsites()
